import com.codezen.helper.Worker;

import flash.events.Event;

import mx.collections.ArrayCollection;
import mx.events.CollectionEvent;
import mx.utils.ObjectUtil;

import utils.serials.Episode;
import utils.serials.EpisodesDB;
import utils.serials.Serial;

private var db:EpisodesDB;
private var dbInit:Boolean;
private var loadCounter:int = -1;
private var loadAllCounter:int = -1;
private var seasonCounter:int = -1;

private function initDatabase():void{
	db = new EpisodesDB();
	// database
	db.addEventListener(Event.INIT, function():void{
		trace('init');
		dbInit = true;
	});
	/*db.addEventListener(Database.CLOSED, function():void{
		//trace('closed');
		// open file
		/*var prefsFile:File = File.applicationStorageDirectory.resolvePath("default.db");
		// del file
		prefsFile.deleteFile();
	});*/
}

private function setEpisodeWatched(ep:Episode):void{
	if(ep == null) return;
	if(ep.view == "true") return;
	ep.view = "true";
	db.saveEpisode(ep);
	db.addEventListener(Event.COMPLETE, onDbSave);
}

private function setEpisodeNotWatched(ep:Episode):void{
	db.delEpisode(ep);
	db.addEventListener(Event.COMPLETE, onDbSave);
}

// set whole season as wached
private function setSeasonWatched():void{
	if(seasonCounter == -1){
		seasonCounter = episodesList.length - 1;
		setBusyCursor();
	}
	episodesList[seasonCounter].view = "true";
	db.addEventListener(Event.COMPLETE, onSeasonSave);
	db.saveEpisode(episodesList[seasonCounter]);
}

private function onSeasonSave(e:Event):void{
	db.removeEventListener(Event.COMPLETE, onSeasonSave);
	seasonCounter--;
	if(seasonCounter < 0){
		removeBusyCursor();
		dbLoadEpisodes();	
		return;
	}
	setSeasonWatched();
}

// set whole season as wached
private function setSeasonNotWatched():void{
	if(seasonCounter == -1){
		seasonCounter = episodesList.length - 1;
		setBusyCursor();
	}
	db.addEventListener(Event.COMPLETE, onSeasonDel);
	db.delEpisode(episodesList[seasonCounter]);
}

private function onSeasonDel(e:Event):void{
	db.removeEventListener(Event.COMPLETE, onSeasonDel);
	seasonCounter--;
	if(seasonCounter < 0){
		removeBusyCursor();
		dbLoadEpisodes();	
		return;
	}
	setSeasonNotWatched();
}

// load series list from DB
private function dbLoadSeries():void{
	db.addEventListener(Event.COMPLETE, onSeriesList);
	db.getSeriesList();
}

private function onSeriesList(e:Event):void{
	// remove
	db.removeEventListener(Event.COMPLETE, onSeriesList);
	// create new list
	iviewSeriesList = new ArrayCollection();
	// parse if something there
	if(db.result != null && db.result.data != null){
		var obj:Object;
		var s:Serial;
		for each(obj in db.result.data){
			// create serial
			s = new Serial();
			// set data
			s.id = obj.serial_id;
			s.bimg = obj.serial_bimg;
			s.info = obj.serial_info;
			s.original = obj.serial_original;
			s.title = obj.serial_title;
			s.simg = obj.serial_simg;
			// add
			iviewSeriesList.addItem(s);
		}
		
		// create sort by names
		var sort:Sort = new Sort();
		sort.fields = [new SortField("title")];
		
		// sort
		iviewSeriesList.sort = sort;
		iviewSeriesList.refresh();
		
		// clean
		sort = null;
		obj = null;
		s = null;
	}
	
	//dbAniLoadSeries();
}

// load saved episodes from db
private function dbLoadSaveEpisodes():void{
	db.addEventListener(Event.COMPLETE, onSavedEpisodeList);
	db.getSavedEpisodesList();
}

private function onSavedEpisodeList(e:Event):void{
	// remove
	db.removeEventListener(Event.COMPLETE, onSavedEpisodeList);
	// create new list
	savedEpisodes = new ArrayCollection();
	
	// parse if something there
	if(db.result != null && db.result.data != null){
		var obj:Object;
		var ep:Episode;
		for each(obj in db.result.data){
			// create serial
			ep = new Episode();
			// set data
			ep.serial_id = obj.serial_id;
			ep.serial_bimg = obj.serial_bimg;
			ep.serial_info = obj.serial_info;
			ep.serial_original = obj.serial_original;
			ep.serial_title = obj.serial_title;
			ep.serial_simg = obj.serial_simg;
			ep.id = obj.id;
			ep.image = obj.image;
			ep.num = obj.num;
			ep.season = obj.season;
			ep.title = obj.title;
			ep.tmark = obj.tmark;
			ep.video = obj.video;
			ep.view = obj.view;
			// add
			savedEpisodes.addItem(ep);
		}
		
		// create sort by names
		var sort:Sort = new Sort();
		sort.fields = [new SortField("title")];
		
		// sort
		savedEpisodes.sort = sort;
		savedEpisodes.refresh();
		
		// clean
		sort = null;
		obj = null;
		ep = null;
	}
	
	dbAniLoadSaveEpisodes();
}

// load new episodes from db
private function dbLoadNewEpisodes():void{
	if(loadCounter == -1 && lastEpisodes != null && lastEpisodes.length > 0){
		loadCounter = lastEpisodes.length - 1;
	}
	db.addEventListener(Event.COMPLETE, onLoadComplete);
	db.checkEpisode(lastEpisodes[loadCounter]);
}

private function onLoadComplete(e:Event):void{
	// remove ev. list
	db.removeEventListener(Event.COMPLETE, onLoadComplete);
	// check
	if(db.result.data != null){
		lastEpisodes[loadCounter].view = "true";
	}else{
		lastEpisodes[loadCounter].view = null;
	}
	// continue
	loadCounter--;
	if(loadCounter < 0){
		lastEpisodes.refresh();
		// load watch series from db
		dbLoadSeries();
		// gc
		startGCCycle();
		return;
	} 
	dbLoadNewEpisodes();
}

// remove whole series from DB
private function dbRemoveSeries():void{
	db.addEventListener(Event.COMPLETE, onDbSave);
	db.removeSeries(currentSeries);
}

// load series episodes from DB
private function dbLoadEpisodes():void{
	if(loadAllCounter == -1){
		loadAllCounter = episodesList.length - 1;
	}
	db.addEventListener(Event.COMPLETE, onEpisodesLoadComplete);
	db.checkEpisode(episodesList[loadAllCounter]);
}

private function onEpisodesLoadComplete(e:Event):void{
	// remove
	db.removeEventListener(Event.COMPLETE, onEpisodesLoadComplete);
	// check
	if(db.result.data != null){
		episodesList[loadAllCounter].view = "true";
	}else{
		episodesList[loadAllCounter].view = null;
	}
	// continue
	loadAllCounter--;
	if(loadAllCounter < 0){
		episodesList.refresh();
		// load watch series from db
		dbLoadSeries();
		// gc
		startGCCycle();
		return;
	} 
	dbLoadEpisodes();
}

private function onDbSave(e:Event):void{
	db.removeEventListener(Event.COMPLETE, onDbSave);

	// work
	if(currentState == "Main" || (currentState == "Player" && oldState == "Main") ){
		dbLoadNewEpisodes();
	}
	if(currentState == "Series" || (currentState == "Player" && oldState == "Series") ){
		dbLoadEpisodes();
	}
	//trace( ObjectUtil.toString(db.result) );
}